using System.Configuration;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebControls;
using System.Data;
using System;
using System.Collections;
using Microsoft.SharePoint;
using System.Diagnostics;
using System.Web.UI;

namespace RequiredCheckboxFieldTypeSolution
{

    // custom field type uses helper class to initialize and render control
    public class RequiredCheckboxFieldControl : BaseFieldControl
    {
        private CheckBox cb;

        public override string DisplayTemplateName
        {
            get { return @"MacawMastWss3TemplatesRequiredCheckboxControlDisplay"; }
        }

        public override object Value
        {
            get
            {
                EnsureChildControls();

                return null;
            }
            set
            {
                EnsureChildControls();
            }
        }

        protected override void CreateChildControls()
        {
            if (Field == null)
            {
                return;
            }

            base.CreateChildControls();

            if (ControlMode == SPControlMode.Display && ItemFieldValue != null)
            {
                string mlsfv = (string)ItemFieldValue;
                return;
            }

            RequiredCheckboxField cf = (RequiredCheckboxField)Field;

            cb = new CheckBox();
            cb.ID = "Checkbox";            
            cb.Text = cf.Text;
            this.Controls.Add(cb);

            this.Controls.Add(new LiteralControl("<br/>"));

            CustomValidator cv = new CustomValidator();
            cv.CssClass = "ms-formvalidation";
            cv.ErrorMessage = cf.ErrorMessage;
            cv.ServerValidate += new ServerValidateEventHandler(cv_ServerValidate);
            this.Controls.Add(cv);
        }

        void cv_ServerValidate(object source, ServerValidateEventArgs args)
        {
            EnsureChildControls();
            if (cb != null && !cb.Checked)
            {
                args.IsValid = false;
            }
            else
            {
                args.IsValid = true;
            }
        }
    }
}
